package ext.tianma.bom.service;

import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ext.com.iba.IBAUtil;
import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.bom.util.CSCIBA;
import ext.tianma.bom.util.ChangeUtil;
import ext.tianma.bom.util.ClassificationUtil;
import ext.tianma.bom.util.CreateNewPartFormUtil;
import ext.tianma.bom.util.DBUtil;
import ext.tianma.bom.util.EnumerationUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.LWCUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.bom.util.WfUtil;
import ext.tianma.part.SemfinishGoodUtil;
import ext.tianma.part.forms.CreateNewPartFormProcessor;
import ext.workflow.WorkFlowUtil;
import wt.change2.ChangeHelper2;
import wt.change2.ChangeNoticeComplexity;
import wt.change2.ChangeOrderIfc;
import wt.change2.Changeable2;
import wt.change2.WTChangeActivity2;
import wt.change2.WTChangeOrder2;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.method.RemoteMethodServer;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTUser;
import wt.part.QuantityUnit;
import wt.part.Source;
import wt.part.WTPart;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.type.TypeDefinitionReference;
import wt.type.TypedUtility;
import wt.type.TypedUtilityServiceHelper;
import wt.util.WTException;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfBlock;
import wt.workflow.engine.WfContainer;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.work.WfAssignmentState;
import wt.workflow.work.WorkItem;

/**
 * 配套物料申请
 * 
 * @author gjw
 *
 */

@Controller
@RequestMapping({ "/MaterialsApplication" })
public class MaterialsApplicationService {
	@Autowired
	HttpServletRequest request;

	private static final Logger log = LogR.getLogger(MaterialsApplicationService.class.getName());

	private static String MaterialsApplicationName = "配套物料申请";// 配套物料申请名称 开头

	private static String defaultECA = "defaultECA"; // 更改任务 默认名称

	private static String softtyepe_MaterialsApp = "cn.tianma.MaterialsApplication_WTChangeOrder2";// 配套物料变更通告
																									// key

	// 物料存储库
	private static String partContainerName = "物料库";

	// 变更存储库
	private static String changeContainerName = "变更库";

	// 半成品 cn.tianma.SemiFinishedGood
	private static String softype_SemiFinishedGood = "cn.tianma.SemiFinishedGood";

	// cn.tianma.RawMaterial 原材料
	private static String softype_RawMaterial = "cn.tianma.RawMaterial";

	// 原材料 上偏光片 cn.tianma.TopPolarizer
	private static String softype_TopPolarizer = "cn.tianma.TopPolarizer";

	// 原材料 下偏光片 cn.tianma.BotPolarizer
	private static String softype_BotPolarizer = "cn.tianma.BotPolarizer";

	// 原材料 虚拟偏光片组件 cn.tianma.PhantomPolarizer
	private static String softype_PhantomPolarizer = "cn.tianma.PhantomPolarizer";
	
	// 原材料编码流程
	private static String workflow_RawMaterial = "原材料编码申请流程";
	// 半成品编码流程
	private static String workflow_SemiFinishedGood = "半成品编码申请流程";
	
	private static String split_flag = ";";


	/**
	 * 根据类型及数据创建原材料或半成品
	 * 
	 * @param number
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmCreateMaterialsApplication", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmCreateMaterialsApplication(@RequestBody String data, HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		String datalist = request.getParameter("datalist");
		log.info("======datalist =========" + datalist);
		log.info("======data =========" + data);
		response.setContentType("text/html; charset=UTF-8");
		String result = "";
		boolean enforce = wt.session.SessionServerHelper.manager.setAccessEnforced(false);
		// 逻辑处理
		try {
			JSONObject object = new JSONObject(data);
			result = tmCreateMaterial(object);
		} catch (Exception e) {
			log.info("======tmCreateMaterialsApplication Exception:" + e.getMessage());
			result = TMECOUtil.errorRequestMessage();
			log.debug(e.getMessage());
		}finally{
			wt.session.SessionServerHelper.manager.setAccessEnforced(enforce);
		}

		out.print(result);
	}

	/**
	 * 根据配套物料申请任务 查看本次申请的数据
	 * 
	 * @param number
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmGetMaterialsApplication", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmGetMaterialsApplication(@RequestParam(value = "oid", required = true) String oid,
			@RequestParam(value = "itemoid", required = false) String itemoid,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		log.info("======type =========" + oid);
		response.setContentType("application/json; charset=UTF-8");
		String result = "";
		boolean enforce = wt.session.SessionServerHelper.manager.setAccessEnforced(false);
		// 逻辑处理
		try {
			result = tmGetMaterial(oid,itemoid);
		} catch (Exception e) {
			log.info("==========tmGetMaterialsApplication" + e.getMessage());
			result = TMECOUtil.errorRequestMessage();
			log.debug(e.getMessage());
		}finally{
			wt.session.SessionServerHelper.manager.setAccessEnforced(enforce);
		}

		out.print(result);
	}
	/**
	 * 根据配套物料申请任务 编辑本次申请的数据,并保存
	 * 
	 * @param number
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmEditMaterialsApplication", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmEditMaterialsApplication(@RequestBody String data,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		response.setContentType("application/json; charset=UTF-8");
		String result = "";
		// 逻辑处理
		try {
			JSONObject object = new JSONObject(data);
			result = tmEditMaterial(object);
		} catch (Exception e) {
			log.info("==========tmGetMaterialsApplication" + e.getMessage());
			result = TMECOUtil.errorRequestMessage();
			log.debug(e.getMessage());
		}

		out.print(result);
	}
	/**
	 * 编辑保存配套物料数据
	 * @param object
	 * @return
	 */
	public static String tmEditMaterial(JSONObject object) {
		JSONObject obj = new JSONObject();
		List<String> numberlist = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		try {
			if (object.has("datalist")) {
				JSONArray array = (JSONArray) object.get("datalist");

				WTPart part = null;
				List<WTPart> list = new ArrayList<WTPart>();
				for (int i = 0; i < array.length(); i++) {
					JSONObject ob = (JSONObject) array.get(i);
					String type = "";
					if (ob.has("roottype")) {
						type = ob.getString("roottype");
					}
					// 半成品
					if ("SemiFinishedGood".equals(type)) {
						part = editSemiFinishedGood(ob);
						if (part != null) {
							list.add(part);
							if (!numberlist.contains(part.getNumber())) {
								numberlist.add(part.getNumber());
							}
						}
					} else if ("Material".equals(type)) {
						// 原材料
						part = editMaterial(ob);
						if (part != null) {
							list.add(part);
							if (!numberlist.contains(part.getNumber())) {
								numberlist.add(part.getNumber());
							}
						}
					}
				}

				/*// 创建配套物料申请
				WTChangeOrder2 eco = createMaterialsApplicationECN(list);

				if (eco != null) {
					obj.put("econumber", eco.getNumber());
				}
				obj.put("numberlist", numberlist);*/
				//obj.put("result", "");
				obj.put("numberlist", numberlist);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			log.debug(e.getMessage());
			e.printStackTrace();
		}

		return obj.toString();
	}
	/**
	 * 编辑半成品正式编号 保存至流程变量正式编码中
	 * {"datalist":"[{C1,"C1Test001"},{C3,"C3Test001"},{C2,"C2Test001"}]"}
	 * 
	 * 
	 * @param oid
	 * @param values
	 * @param response
	 * @throws Exception
	 * 
	 */
	@RequestMapping(value = "/tmEditMaterialsNumber", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmEditMaterialsNumber(@RequestBody String values, HttpServletResponse response) throws Exception {
		log.info("=====values:" + values);
		String result = "";
		PrintWriter out = response.getWriter();
		try {
			JSONObject obj = new JSONObject(values);
			if (obj.has("datalist")) {
				String oid = obj.getString("oid");
				response.setContentType("application/json; charset=UTF-8");
				// 逻辑处理
				log.info("===============tmEditMaterialsNumber==========start");
				WorkItem workItem = (WorkItem) GenericUtil.REF_FACTORY.getReference(oid).getObject();
				// 获取活动
				WfActivity activity = (WfActivity) workItem.getSource().getObject();
				// 获取活动名称
				String activityname = activity.getName();
				// 获取工作流
				WfProcess process = WorkFlowUtil.GetWfProcess(oid);
				// 获取pbo
				Object pbo = workItem.getPrimaryBusinessObject().getObject();
				log.info("============editNumber enter======process name:" + process.getName()
						+ "===activityname:" + activityname);
				JSONArray array = new JSONArray(obj.getString("datalist"));
				if (process.getName().indexOf("配套物料申请流程") != -1 && "半成品审核(BOM工程师)".equals(activityname.toString())) {
					log.info("============editNumber enter======");
					WTChangeOrder2 eco = null;
					if (pbo instanceof WTChangeOrder2) {
						eco = (WTChangeOrder2) pbo;
					}
					if (eco != null) {
						// 设置流程变量
						result = setProcessParams(eco, process, array);
					}
				}
			} else {
				result = TMECOUtil.errorRequestMessage();
			}
		} catch (JSONException e) {
			log.info(e);
			result = TMECOUtil.errorUpdateMessage(e.getMessage());
		}
		log.info("===============editNumber==========end");

		out.print(result);
	}

	/**
	 * 设置正式编码变量 格式如下： { "C1":"", "C2","", "C3","" "C5":"", ... }
	 * 
	 * @param eco
	 * @param process
	 * @param request
	 */
	public static String setProcessParams(WTChangeOrder2 eco, WfProcess process, JSONArray array) {
		JSONObject obj = new JSONObject();
		String result = "";
		List<String> numberlist = new ArrayList<String>();
		log.info("============setProcessParams enter======");
		if (process != null && eco != null) {
			String data = "";
			JSONObject object = new JSONObject();
			ProcessData processData = process.getContext();
			try {
				QueryResult queryResultECA = ChangeHelper2.service.getChangeActivities(eco);
				if (queryResultECA != null) {
					while (queryResultECA.hasMoreElements()) {
						WTChangeActivity2 eca = (WTChangeActivity2) queryResultECA.nextElement(); // 获取ECA
						log.info("============setProcessParams eca======" + eca.getName() + "---number:"
								+ eca.getNumber());
						if (eca != null) {
							// 受影响对象
							QueryResult queryResultPart = ChangeHelper2.service.getChangeablesBefore(eca);
							if (queryResultPart != null) {
								while (queryResultPart.hasMoreElements()) {
									Changeable2 changeable = (Changeable2) queryResultPart.nextElement();
									if (changeable != null && changeable instanceof WTPart) {
										WTPart part = (WTPart) changeable;
										String Type = (String) ext.tianma.bom.util.IBAUtil.getIBAValue(part,
												"SemiFinishedGoodType");
										log.info("===Typevalue:" + Type);
										if (!StringUtil.isNullOrEmpty(Type)) {
											String value = "";
											for (int i = 0; i < array.length(); i++) {
												JSONObject objchild = (JSONObject) array.get(i);
												if (objchild.has(Type)) {
													value = objchild.getString(Type);
												}
											}

											log.info("====value:" + value);
											// 若页面存在对应的值 则放在变量中 否则提示分类未填写
											if (!StringUtil.isNullOrEmpty(value)) {
												try {
													WTPart checkpart = GenericUtil.getPart(value, "");
													if (checkpart != null) {
														result += value + "正式编号已存在;";
													} else {
														if (numberlist.contains(value)) {
															result += value + "正式编号不能重复;";
														} else {
															numberlist.add(value);
														}
														boolean flag = SemfinishGoodUtil.checkNum(value, part);
														if (!flag) {
															result += value + "该镀膜类型与编码末位规则不符;";
														} else {
															object.put(Type, value);
														}
													}
												} catch (Exception e1) {
													log.error(e1.getMessage(), e1);
													e1.printStackTrace();
												}
											} else {
												result += part.getNumber() + "的正式编号未填写;";
											}
										} else {
											result += part.getNumber() + "的分类未填写;";
										}

									}
								}
							}
						}
					}
				}
				data = object.toString();
				log.info("======data:" + data);
				log.info("======processData number before :" + processData.getValue("正式编码"));

				// WfVariable VariableMainType =
				// process.getContext().getVariable("正式编码");
				// VariableMainType.setValue(data);
				if("".equals(result)){
					processData.setValue("正式编码", data);
					process.setContext(processData);
					wt.fc.PersistenceHelper.manager.save(process);
					log.info("======processData number after:" + processData.getValue("正式编码"));
					wt.fc.PersistenceHelper.manager.refresh(process);
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		try {
			obj.put("result", result);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return obj.toString();
	}

	/**
	 * 通过配套物料申请任务获取 本次受影响对象的IBA属性
	 * 
	 * @param oid
	 * @return
	 */
	public static String tmGetMaterial(String oid,String itemoid) {
		JSONObject obj = new JSONObject();
		String result = "";
		JSONArray array = new JSONArray();
		if(isNullOrEmpty(itemoid)){
			return obj.toString();
		}
		try {
			//取流程变量值
			ReferenceFactory rf = new ReferenceFactory();
			WorkItem wi = (WorkItem) rf.getReference(itemoid).getObject();
			WfActivity wfAct = (WfActivity) wi.getSource().getObject();
			WfContainer wfcont = (WfContainer) wfAct.getParentProcessRef().getObject();
			WfProcess process = null;
			if (wfcont instanceof WfBlock) {
				WfBlock wfblock = (WfBlock)wfcont;
				process =wfblock.getParentProcess();
			} else {
				process = (WfProcess) wfcont;
			}
			ProcessData processData = process.getContext();
			Object object = processData.getValue("正式编码");
			//正式编码
			String number = "";
			JSONObject ob = new JSONObject();
			if(object != null){
				number = (String)object;
				log.info("====look 正式编码:"+number);
				if(!isNullOrEmpty(number.trim())){
					ob = new JSONObject(number);
				}
			}
			
			
			
			WTChangeOrder2 eco = (WTChangeOrder2) BOMHelp.REF_FACTORY.getReference(oid).getObject();
			if (eco != null) {
				QueryResult queryResultECA = ChangeHelper2.service.getChangeActivities(eco);
				if (queryResultECA != null) {
					while (queryResultECA.hasMoreElements()) {
						WTChangeActivity2 eca = (WTChangeActivity2) queryResultECA.nextElement(); // 获取ECA
						if (eca != null) {
							// 受影响对象
							QueryResult queryResultPart = ChangeHelper2.service.getChangeablesBefore(eca);
							if (queryResultPart != null) {
								while (queryResultPart.hasMoreElements()) {
									Changeable2 changeable = (Changeable2) queryResultPart.nextElement();
									if (changeable != null && changeable instanceof WTPart) {
										WTPart part = (WTPart) changeable;
										// put 受影响对象的属性
										putData(part, array,ob);
									}
								}
							}
						}
					}
				}
			}

		} catch (Exception e) {
			log.info("======tmGetMaterial 1=========" + e);
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				obj.put("datalist", array);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return obj.toString();
	}

	public static void putData(WTPart part, JSONArray array,JSONObject ob) {
		JSONObject object = new JSONObject();
		Hashtable values;
		try {
			values = IBAUtil.getIBAValues(part);
			Iterator iter = values.keySet().iterator();
			while (iter.hasNext()) {
				String key = iter.next().toString();
			//	log.info("====putData key:" + key);
			//	log.info("====putData value:" + (values.get(key).getClass()));
				if (values.get(key) instanceof String) {
					String value = (String) values.get(key);
					// String displayname = queryDisplayName(key);
					if("partSupplier".equals(key) && !isNullOrEmpty(value)){
						String result = "";
						result = EnumerationUtil.getEnumerationDisplayValue("供应商名称", value);
						if(!isNullOrEmpty(result)){
							value = result;
						}
					}
					if("partNumberEffectiveSite".equals(key) && !isNullOrEmpty(value)){
						String result = "";
						result = EnumerationUtil.getEnumerationDisplayValue("料号生效产地", value);
						if(!isNullOrEmpty(result)){
							value = result;
						}
					}
					if("partInspectionStandard".equals(key) && !isNullOrEmpty(value)){
						String result = "";
						result = EnumerationUtil.getEnumerationDisplayValue("检验标准", value);
						if(!isNullOrEmpty(result)){
							value = result;
						}
					}
					if("partEnvProtectionCategory".equals(key) && !isNullOrEmpty(value)){
						String result = "";
						result = EnumerationUtil.getEnumerationDisplayValue("环保类别", value);
						if(!isNullOrEmpty(result)){
							value = result;
						}
					}
					object.put(key, value);
					// otherorigin 其他生效地及源类型
					if ("其他生效地及源类型".equals(key)) {
						object.put("otherorigin", value);
					}
				} else if (values.get(key) instanceof Timestamp) {
					Timestamp time = (Timestamp) values.get(key);
					// String displayname = queryDisplayName(key);
					object.put(key, time);
				} else if (values.get(key) instanceof Float) {
					Float f = (Float) values.get(key);
					// String displayname = queryDisplayName(key);
					object.put(key, f);
				}

			}
			String type = GenericUtil.getTypeId(part);
			
			// 分类属性
			String classificationATT = "";
			// 类型
			if (type.indexOf(softype_SemiFinishedGood) != -1) {
				// roottype SemiFinishedGood
				object.put("roottype", "SemiFinishedGood");
				object.put("createType", "半成品");
				//cn.tianma.synchysis
				String synchysis = "";
				try{
					 synchysis  = (String) LWCUtil.getValue(part, "synchysis");
				}catch(Exception e){
					synchysis  = (String) LWCUtil.getValue(part, "cn.tianma.synchysis");
				}
				log.info("==synchysis:"+synchysis);
				object.put("synchysis", synchysis==null?"":synchysis);
				// 半成品分类：
				String SemiFinishedGoodType = (String) LWCUtil.getValue(part, "SemiFinishedGoodType");
				String numberA  = "";
				if(!isNullOrEmpty(SemiFinishedGoodType) && ob.has(SemiFinishedGoodType)){
					//正式编号
					numberA  = ob.get(SemiFinishedGoodType) ==null?"":(String)ob.get(SemiFinishedGoodType);
				}
				object.put("numberA", numberA);
				classificationATT = getClassificationATT(part);
				object.put("classificationATT", classificationATT==null?"":classificationATT);
			} else if (type.indexOf(softype_RawMaterial) != -1) {
				object.put("roottype", "Material");
				if (type.indexOf(softype_PhantomPolarizer) != -1) {
					object.put("createType", "虚拟偏光片组件");
					// 避免 前端key值 重复
					if (object.has("partDrawingNumber")) {
						object.put("partDrawingNumber1", object.getString("partDrawingNumber") == null ? ""
								: object.getString("partDrawingNumber"));
					}
					if (object.has("MtlNumofPOLTop")) {
						object.put("MtlNumofPOLTop1",
								object.has("MtlNumofPOLTop") ? object.getString("MtlNumofPOLTop") : "");
					}
					if (object.has("MtlNumofPOLBtn")) {
						object.put("MtlNumofPOLBtn1",
								object.has("MtlNumofPOLBtn") ? object.getString("MtlNumofPOLBtn") : "");
					}
					object.put("partDrawingNumber", "");
					object.put("MtlNumofPOLBtn", "");
					object.put("MtlNumofPOLTop", "");
				}else if(type.indexOf(softype_BotPolarizer) != -1){
					object.put("createType", "下偏光片");
				}else if(type.indexOf(softype_TopPolarizer) != -1){
					object.put("createType", "上偏光片");
				}
			}
			// 源
			object.put("source", part.getSource().toString());
			//
			object.put("defaultUnit", part.getDefaultUnit().toString());
			object.put("number", part.getNumber());
			object.put("name", part.getName());
			array.put(object);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.info("====putData Exception:" + e.getMessage());
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}

	}

	public static String tmCreateMaterial(JSONObject object) {
		JSONObject obj = new JSONObject();
		List<String> numberlist = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		try {
			if (object.has("datalist")) {
				JSONArray array = (JSONArray) object.get("datalist");

				WTPart part = null;
				List<WTPart> list = new ArrayList<WTPart>();
				for (int i = 0; i < array.length(); i++) {
					JSONObject ob = (JSONObject) array.get(i);
					String type = "";
					if (ob.has("roottype")) {
						type = ob.getString("roottype");
					}
					// 半成品
					if ("SemiFinishedGood".equals(type)) {
						part = createSemiFinishedGood(ob);
						if (part != null) {
							list.add(part);
							if (!numberlist.contains(part.getNumber())) {
								numberlist.add(part.getNumber());
							}
						}
					} else if ("Material".equals(type)) {
						// 原材料
						part = createMaterial(ob);
						if (part != null) {
							list.add(part);
							if (!numberlist.contains(part.getNumber())) {
								numberlist.add(part.getNumber());
							}
						}
					}
				}
				
				
				// 创建配套物料申请
				WTChangeOrder2 eco = createMaterialsApplicationECN(list);

				if (eco != null) {
					obj.put("econumber", eco.getNumber());
				}
				//关闭原先的编码流程
				closeOldNumberWF(numberlist);
				
				obj.put("numberlist", numberlist);

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			log.debug(e.getMessage());
			e.printStackTrace();
		}

		return obj.toString();
	}
	/**
	 * 关闭原编码流程
	 * @param numberlist   编号集合
	 */
	public static void closeOldNumberWF(List<String> numberlist){
		for(String number : numberlist){
			//log.info("=====closeOldNumberWF=============="+number);
			try {
				WTPart part = GenericUtil.getPart(number.trim(), "", "");
				if(part!=null){
					//CLOSED_COMPLETED_EXECUTED
					QueryResult qr = WfEngineHelper.service.getAssociatedProcesses(part, WfState.OPEN_RUNNING, null);
					WfProcess process = null;
					while (qr.hasMoreElements()) {
						process = (WfProcess) qr.nextElement();
						log.info("=====closeOldNumberWF:"+number+"---"+process.getTemplate().getName());
						if (process.getTemplate().getName().equals(workflow_RawMaterial) ) {
							QueryResult result = WfUtil.getUncompletedWorkItems(process, "原材料提交");
							log.info("====workflow_RawMaterial result"+result.size());
							while(result.hasMoreElements()){
								WorkItem item =  (WorkItem)result.nextElement();
								//COMPLETED 
								item.setStatus(WfAssignmentState.COMPLETED);
								item.setComplete("");
							//	PersistenceServerHelper.manager.update(item);
								//PersistenceHelper.manager.refresh(item);
								PersistenceHelper.manager.delete(item);
							}
							process.setState(WfState.CLOSED_COMPLETED);
							PersistenceServerHelper.manager.update(process);
							PersistenceHelper.manager.refresh(process);
						}else if(process.getTemplate().getName().equals(workflow_SemiFinishedGood)){
							QueryResult result = WfUtil.getUncompletedWorkItems(process, "半成品提交");
							log.info("====workflow_SemiFinishedGood result"+result.size());
							while(result.hasMoreElements()){
								WorkItem item =  (WorkItem)result.nextElement();
								//COMPLETED 
								item.setStatus(WfAssignmentState.COMPLETED);
								item.setComplete("");
								//PersistenceServerHelper.manager.update(item);
								//PersistenceHelper.manager.refresh(item);
								PersistenceHelper.manager.delete(item);
							}
							process.setState(WfState.CLOSED_COMPLETED);
							PersistenceServerHelper.manager.update(process);
							PersistenceHelper.manager.refresh(process);
						}
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		
	}
	/**
	 * 创建配套物料申请 变更通告 并将申请物料 添加至受影响对象
	 * 
	 * @return
	 * @throws Exception
	 */
	public static WTChangeOrder2 createMaterialsApplicationECN(List<WTPart> list) {
		WTChangeOrder2 newECN = null;
		try {
			Calendar calendar = Calendar.getInstance();// 获得系统当前日期
			int year = calendar.get(Calendar.YEAR);
			int moth = calendar.get(Calendar.MONTH) + 1;
			SimpleDateFormat sy = new SimpleDateFormat("yyyyMMddHHmmss");
			String time = sy.format(new Date());
			newECN = WTChangeOrder2.newWTChangeOrder2(MaterialsApplicationName + time);

			String number = DBUtil.getNextValue("WTCHANGEORDERID_seq", 5);
			log.info("===order number:" + number);
			// newECN.setNumber("DCN"+year+""+moth+number);
			newECN.setNumber(year + "" + moth + number);

			log.info("===order name:" + MaterialsApplicationName + time);
			newECN.setName(MaterialsApplicationName + time);

			newECN.setChangeNoticeComplexity(ChangeNoticeComplexity.BASIC);

			// TypeIdentifier typeidentifier =
			// CoreMetaUtility.getTypeIdentifier(softtyepe_MaterialsApp);
			// newECN = (WTChangeOrder2) CoreMetaUtility.setType(newECN,
			// typeidentifier);
			TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference(softtyepe_MaterialsApp);
			newECN.setTypeDefinitionReference(typeDefinitionRef);

			// newECN.setDescription("test");
			WTContainer con = getContainerByName(partContainerName);
			newECN.setContainer(con);
			String path = "/Default/配套物料";
			/*Folder folder = GenericUtil.getFolder(path, con);
			FolderHelper.assignLocation(newECN, folder);*/

			Folder folder2=GenericUtil.getFolder(path,con);
			FolderHelper.assignLocation((FolderEntry)newECN, folder2);
			
			// newECN = (WTChangeOrder2)
			// ChangeHelper2.service.saveChangeOrder((ChangeOrderIfc) newECN);
			newECN = (WTChangeOrder2) PersistenceHelper.manager.save(newECN);

			// add eca to ECO
			WTChangeActivity2 eca = autoECAFromECN(newECN, defaultECA);

			// add list to ECA
			ChangeUtil.addChangeableBeforeToChangeNotice(newECN, list, eca);
		} catch (Exception e) {
			e.printStackTrace();
			log.debug(e.getMessage());
		} finally {
			// wt.session.SessionHelper.manager.setPrincipal(prin.getName());
		}
		return newECN;

	}

	/**
	 * 在ECO 中 创建ECA
	 * 
	 * @param eco
	 * @param name
	 * @return
	 */
	public static WTChangeActivity2 autoECAFromECN(WTChangeOrder2 eco, String name) {
		wt.org.WTPrincipalReference sessioner = null;
		try {
			sessioner = wt.session.SessionHelper.manager.getPrincipalReference(); // 获取当前参与人员
			if (name == null || name.equals(""))
				name = eco.getName();
			WTChangeActivity2 eca = null;
			QueryResult qrr = ChangeHelper2.service.getChangeActivities(eco);
			while (qrr.hasMoreElements()) {
				Object oo = qrr.nextElement();
				if (oo instanceof WTChangeActivity2) {
					WTChangeActivity2 ca = (WTChangeActivity2) oo;
					if (ca.getName().equals(name)) {
						eca = ca;
						break;
					}
				}
			}
			if (eca != null) {
				return eca;
			}
		} catch (WTException wte) {
			log.debug(wte.getMessage());
		}
		return autoECAFromECN(eco, name, sessioner, sessioner);
	}

	/**
	 * 若不存在默认ECA 则创建更改任务
	 * 
	 * @param eco
	 * @param s
	 * @param s2
	 * @param s3
	 * @return
	 */
	public static WTChangeActivity2 autoECAFromECN(WTChangeOrder2 eco, String s, wt.org.WTPrincipalReference s2,
			wt.org.WTPrincipalReference s3) {
		WTChangeActivity2 eca = null;
		try {
			ChangeOrderIfc changeorderifc = (ChangeOrderIfc) eco;
			eca = WTChangeActivity2.newWTChangeActivity2(s);
			eca.setContainer(eco.getContainer());
			eca.setDescription(s);
			eca = (WTChangeActivity2) ChangeHelper2.service.saveChangeActivity(changeorderifc, eca);
			wt.team.Team team = wt.team.TeamHelper.service.getTeam(eca);
			team.addPrincipal(wt.project.Role.toRole("ASSIGNEE"), s2.getPrincipal());
			team.addPrincipal(wt.project.Role.toRole("REVIEWER"), s3.getPrincipal());
			team = (wt.team.Team) PersistenceHelper.manager.refresh(team);
			team = (wt.team.Team) PersistenceHelper.manager.save(team);
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		return eca;
	}

	/**
	 * 创建半成品
	 * 
	 * C1 ----- C9
	 * 
	 * @param ob
	 */
	public static WTPart createSemiFinishedGood(JSONObject ob) {
		WTPart part = null;
		try {
			Hashtable<String, String> ibamap = new Hashtable<String, String>();
			// String type = ob.getString("type");

			// 通用属性
			// 类型：半成品
			// String createType = ob.getString("createType");
			// 创建为成品： 否
			// String endItem = ob.getString("endItem");
			// 源：制造，购买，外协加工、虚拟件 make/buy/SUBCONTRACTOR/PHANTOM
			String source = ob.getString("source");
			// 视图：Design
			// String view = ob.getString("view");
			// 申请原因
			String partApplicationReason = ob.getString("partApplicationReason");

			if (!isNullOrEmpty(partApplicationReason)) {
				ibamap.put("partApplicationReason", partApplicationReason);
			}

			// 料号生效产地
			String partNumberEffectiveSite = ob.getString("partNumberEffectiveSite");

			if (!isNullOrEmpty(partNumberEffectiveSite)) {
				if (partNumberEffectiveSite.indexOf("（") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("（"));
				} else if (partNumberEffectiveSite.indexOf("(") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("("));
				}
				ibamap.put("partNumberEffectiveSite", partNumberEffectiveSite.trim());
			}

			// 其他生效地及源类型（如只需在一地生效，请选“无”）
			String otherorigin = ob.getString("otherorigin");

			if (!isNullOrEmpty(otherorigin)) {
				ibamap.put("otherorigin", otherorigin);
			}
			// 产品尺寸：
			String finishedGoodSize = ob.getString("finishedGoodSize");

			if (!isNullOrEmpty(finishedGoodSize)) {
				// 转double判断是否符合格式
				/*
				 * try { double f = Double.parseDouble(finishedGoodSize); //
				 * 保留两位 String size = String.format("%.2f", f);
				 * ibamap.put("finishedGoodSize", size); } catch (Exception e) {
				 * log.info("产品尺寸不符合格式"); }
				 */

				ibamap.put("finishedGoodSize", finishedGoodSize);
			}
			// 线体： finishedGoodLineBody
			String finishedGoodLineBody = ob.getString("finishedGoodLineBody");

			if (!isNullOrEmpty(finishedGoodLineBody)) {
				ibamap.put("finishedGoodLineBody", finishedGoodLineBody);
			}

			// 图纸编号/工艺文件编号
			String partDrawingNumber = ob.getString("partDrawingNumber");

			if (!isNullOrEmpty(partDrawingNumber)) {
				ibamap.put("partDrawingNumber", partDrawingNumber);
			}

			// 检验标准
			String partInspectionStandard = ob.getString("partInspectionStandard");

			log.info("======createSemiFinishedGood  partInspectionStandard:" + partInspectionStandard);

			if (!isNullOrEmpty(partInspectionStandard)) {
				ibamap.put("partInspectionStandard", partInspectionStandard);
			}

			// 供应商：
			String partSupplier = ob.getString("partSupplier");

			if (!isNullOrEmpty(partSupplier)) {
				//ibamap.put("partSupplier", partSupplier);
				//key 显示名称  value 内部值
				String value = "";
				Map<String,String> map = EnumerationUtil.getEnumerationValues2("供应商名称");
				if(map.containsKey(partSupplier)){
					value = map.get(partSupplier);
				}
				if(!isNullOrEmpty(value)){
					ibamap.put("partSupplier", value);
				}else{
					ibamap.put("partSupplier", partSupplier);
				}
			}

			// 环保类别
			String partEnvProtectionCategory = ob.getString("partEnvProtectionCategory");

			if (!isNullOrEmpty(partEnvProtectionCategory)) {
				ibamap.put("partEnvProtectionCategory", partEnvProtectionCategory);
			}

			// 备注说明：
			String partNote = ob.getString("partNote");

			if (!isNullOrEmpty(partNote)) {
				ibamap.put("partNote", partNote);
			}

			// 镀膜类型（非C7/C8半成品请选NA）:
			String Coatingtype = ob.getString("Coatingtype");

			if (!isNullOrEmpty(Coatingtype)) {
				ibamap.put("Coatingtype", Coatingtype);
			}

			// 创建CAD文档： 是否创建CAD文档
			// String CAD = ob.getString("CAD");
			// 检入后保持检出状态
			// String checkout = ob.getString("checkout");

			// 专用属性
			/*
			 * 编号：自动生成
			 * 
			 * key:number
			 * 
			 * 名称：自动生成
			 * 
			 * key:name
			 */

			// 是否混版及混版尺寸
			String synchysis = ob.getString("synchysis");
			log.info("========synchysis:" + synchysis);
			if (!isNullOrEmpty(synchysis)) {
				ibamap.put("cn.tianma.synchysis", synchysis);
				log.info("=====synchysis:" + synchysis);
			}

			// 默认单位：
			String defaultUnit = ob.getString("defaultUnit");
			QuantityUnit qunit = null;
			if (!isNullOrEmpty(defaultUnit)) {
				qunit = QuantityUnit.toQuantityUnit(defaultUnit);
			}
			// 分类：
			// String classification = ob.getString("classification");

			// 半成品分类：
			String SemiFinishedGoodType = ob.getString("SemiFinishedGoodType");

			// 分类属性 classificationATT
			String classificationATT = "";
			if (ob.has("classificationATT")) {
				classificationATT = ob.getString("classificationATT");
			}

			if (!isNullOrEmpty(SemiFinishedGoodType)) {
				ibamap.put("SemiFinishedGoodType", SemiFinishedGoodType);
			} /*
				 * else if(!isNullOrEmpty(classification)){
				 * ibamap.put("SemiFinishedGoodType", classification); }
				 */

			// 单玻璃厚度：
			String partSingleGlassThickness = ob.getString("partSingleGlassThickness");
			if (!isNullOrEmpty(partSingleGlassThickness)) {
				ibamap.put("partSingleGlassThickness", partSingleGlassThickness);
			}

			// 切割方式
			String cuttingMode = ob.getString("cuttingMode");
			if (!isNullOrEmpty(cuttingMode)) {
				ibamap.put("cuttingMode", cuttingMode);
			}

			// 加工方式及薄化前后厚度
			String processingModeAndThickness = ob.getString("processingModeAndThickness");

			if (!isNullOrEmpty(processingModeAndThickness)) {
				ibamap.put("processingModeAndThickness", processingModeAndThickness);
			}

			// 集成度（格式如：60PANEL）:
			String Integration = ob.getString("Integration");

			if (!isNullOrEmpty(Integration)) {
				ibamap.put("Integration", Integration);
			}

			// 成品型号
			String finishedGoodType = ob.getString("finishedGoodType");
			if (!isNullOrEmpty(finishedGoodType)) {
				ibamap.put("finishedGoodType", finishedGoodType);
			}

			String partnumber = DBUtil.getNextValue("WTPARTID_seq", 10);

			String partname = DBUtil.getNextValue("variantnameseq", 10);

			WTContainer repcon = getContainerByName(partContainerName);
			
			// WTContainer con = doc.getContainer();
			if (null == repcon) {
				throw new WTException("没有获取到物料库");
			}
			log.info("===repcon:"+repcon.getContainerName()+"---"+repcon.getName());
			part = WTPart.newWTPart();
			TypeDefinitionReference typeDefinitionRef = TypedUtility
					.getTypeDefinitionReference(softype_SemiFinishedGood);
			part.setTypeDefinitionReference(typeDefinitionRef);
			part.setNumber(partnumber);
			String foldStr = "/Default";
			Folder folder = FolderHelper.service.getFolder(foldStr, repcon.getContainerReference());
			log.info("===folder:"+folder.getFolderPath());
			part.setContainer(repcon);
			/*if (folder != null) {
				FolderHelper.assignLocation(part, folder);
			}*/

			part.setOrganization(repcon.getContainer().getOrganization());
			part.setName(partname);
			if (qunit != null) {
				part.setDefaultUnit(qunit);
			}

			// 创建为成品： 否
			part.setEndItem(false);
			/*
			 * if ("否".equals(endItem)) { part.setEndItem(false); } else if
			 * ("是".equals(endItem)) { part.setEndItem(true); }
			 */
			// 源 制造，购买，外协加工、虚拟件 make/buy/SUBCONTRACTOR/PHANTOM

			Source sourcess = Source.toSource("make");
			if (!isNullOrEmpty(source)) {
				if ("制造".equals(source)) {
					sourcess = Source.toSource("make");
				} else if ("购买".equals(source)) {
					sourcess = Source.toSource("buy");
				} else if ("外协加工".equals(source)) {
					sourcess = Source.toSource("SUBCONTRACTOR");
				} else if ("虚拟件".equals(source)) {
					sourcess = Source.toSource("PHANTOM");
				}

			}
			part.setSource(sourcess);

			ViewReference viewRef = null;
			View viewview = ViewHelper.service.getView("Design");
			viewRef = ViewReference.newViewReference(viewview);

			part.setView(viewRef);

			part = (WTPart) PersistenceHelper.manager.save(part);
			//终止原编码流程
			WfEngineHelper.service.terminateObjectsRunningWorkflows(part);
			//end
			IBAUtil.setSoftTypeIBAValues(part, ibamap);
			// 设置分类
			ClassificationUtil.setClassification("wt.part.WTPart", SemiFinishedGoodType, part);
			// 设置分类属性 用于设置不在本次配套申请的编码
			setClassificationATT(classificationATT, SemiFinishedGoodType, part);
			part = (WTPart) LifeCycleHelper.service.setLifeCycleState(part, State.INWORK);

			// CreateNewPartFormProcessor.updateSemiFinishedGoodInfo
			CreateNewPartFormUtil.updateSemiFinishedGoodInfo(part);
			/*
			 * if (!isNullOrEmpty(synchysis)) { //ibamap.put("synchysis",
			 * synchysis); log.info("=====synchysis 22222:"
			 * +synchysis); CSCIBA.setIBAStringValue(part, "synchysis",
			 * synchysis); }
			 */
			log.info("===createSemiFinishedGood end:" + part.getNumber());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return part;
	}
	
	/**
	 * 编辑半成品
	 * 
	 * C1 ----- C9
	 * 
	 * @param ob
	 */
	public static WTPart editSemiFinishedGood(JSONObject ob) {
		WTPart part = null;
		try {
			Hashtable<String, String> ibamap = new Hashtable<String, String>();
			// String type = ob.getString("type");
			if(ob.has("number")){
				String partnumber = ob.getString("number");
				part = GenericUtil.getPart(partnumber, "", "Design");
			}
			if(part == null){
				return part;
			}
			// 通用属性
			// 类型：半成品
			// String createType = ob.getString("createType");
			// 创建为成品： 否
			// String endItem = ob.getString("endItem");
			// 源：制造，购买，外协加工、虚拟件 make/buy/SUBCONTRACTOR/PHANTOM
			String source = ob.getString("source");
			// 视图：Design
			// String view = ob.getString("view");
			// 申请原因
			String partApplicationReason = ob.getString("partApplicationReason");

			if (!isNullOrEmpty(partApplicationReason)) {
				ibamap.put("partApplicationReason", partApplicationReason);
			}

			// 料号生效产地
			String partNumberEffectiveSite = ob.getString("partNumberEffectiveSite");

			if (!isNullOrEmpty(partNumberEffectiveSite)) {
				if (partNumberEffectiveSite.indexOf("（") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("（"));
				} else if (partNumberEffectiveSite.indexOf("(") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("("));
				}
				ibamap.put("partNumberEffectiveSite", partNumberEffectiveSite.trim());
			}

			// 其他生效地及源类型（如只需在一地生效，请选“无”）
			String otherorigin = ob.getString("otherorigin");

			if (!isNullOrEmpty(otherorigin)) {
				ibamap.put("otherorigin", otherorigin);
			}
			// 产品尺寸：
			String finishedGoodSize = ob.getString("finishedGoodSize");

			if (!isNullOrEmpty(finishedGoodSize)) {
				// 转double判断是否符合格式
				/*
				 * try { double f = Double.parseDouble(finishedGoodSize); //
				 * 保留两位 String size = String.format("%.2f", f);
				 * ibamap.put("finishedGoodSize", size); } catch (Exception e) {
				 * log.info("产品尺寸不符合格式"); }
				 */

				ibamap.put("finishedGoodSize", finishedGoodSize);
			}
			// 线体： finishedGoodLineBody
			String finishedGoodLineBody = ob.getString("finishedGoodLineBody");

			if (!isNullOrEmpty(finishedGoodLineBody)) {
				ibamap.put("finishedGoodLineBody", finishedGoodLineBody);
			}

			// 图纸编号/工艺文件编号
			String partDrawingNumber = ob.getString("partDrawingNumber");

			if (!isNullOrEmpty(partDrawingNumber)) {
				ibamap.put("partDrawingNumber", partDrawingNumber);
			}

			// 检验标准
			String partInspectionStandard = ob.getString("partInspectionStandard");

			log.info("======createSemiFinishedGood  partInspectionStandard:" + partInspectionStandard);

			if (!isNullOrEmpty(partInspectionStandard)) {
				ibamap.put("partInspectionStandard", partInspectionStandard);
			}

			// 供应商：
			String partSupplier = ob.getString("partSupplier");

			if (!isNullOrEmpty(partSupplier)) {
				//key 显示名称  value 内部值
				String value = "";
				Map<String,String> map = EnumerationUtil.getEnumerationValues2("供应商名称");
				if(map.containsKey(partSupplier)){
					value = map.get(partSupplier);
				}
				if(!isNullOrEmpty(value)){
					ibamap.put("partSupplier", value);
				}else{
					ibamap.put("partSupplier", partSupplier);
				}
			}

			// 环保类别
			String partEnvProtectionCategory = ob.getString("partEnvProtectionCategory");

			if (!isNullOrEmpty(partEnvProtectionCategory)) {
				ibamap.put("partEnvProtectionCategory", partEnvProtectionCategory);
			}

			// 备注说明：
			String partNote = ob.getString("partNote");

			if (!isNullOrEmpty(partNote)) {
				ibamap.put("partNote", partNote);
			}

			// 镀膜类型（非C7/C8半成品请选NA）:
			String Coatingtype = ob.getString("Coatingtype");

			if (!isNullOrEmpty(Coatingtype)) {
				ibamap.put("Coatingtype", Coatingtype);
			}

			// 创建CAD文档： 是否创建CAD文档
			// String CAD = ob.getString("CAD");
			// 检入后保持检出状态
			// String checkout = ob.getString("checkout");

			// 专用属性
			/*
			 * 编号：自动生成
			 * 
			 * key:number
			 * 
			 * 名称：自动生成
			 * 
			 * key:name
			 */

			// 是否混版及混版尺寸
			String synchysis = ob.getString("synchysis");
			log.info("========synchysis:" + synchysis);
			if (!isNullOrEmpty(synchysis)) {
				ibamap.put("cn.tianma.synchysis", synchysis);
				log.info("=====synchysis:" + synchysis);
			}

			// 默认单位：
			String defaultUnit = ob.getString("defaultUnit");
			QuantityUnit qunit = null;
			if (!isNullOrEmpty(defaultUnit)) {
				qunit = QuantityUnit.toQuantityUnit(defaultUnit);
			}
			// 分类：
			// String classification = ob.getString("classification");

			// 半成品分类：
			String SemiFinishedGoodType = ob.getString("SemiFinishedGoodType");

			// 分类属性 classificationATT
			String classificationATT = "";
			if (ob.has("classificationATT")) {
				classificationATT = ob.getString("classificationATT");
			}

			if (!isNullOrEmpty(SemiFinishedGoodType)) {
				ibamap.put("SemiFinishedGoodType", SemiFinishedGoodType);
			} /*
				 * else if(!isNullOrEmpty(classification)){
				 * ibamap.put("SemiFinishedGoodType", classification); }
				 */

			// 单玻璃厚度：
			String partSingleGlassThickness = ob.getString("partSingleGlassThickness");
			if (!isNullOrEmpty(partSingleGlassThickness)) {
				ibamap.put("partSingleGlassThickness", partSingleGlassThickness);
			}

			// 切割方式
			String cuttingMode = ob.getString("cuttingMode");
			if (!isNullOrEmpty(cuttingMode)) {
				ibamap.put("cuttingMode", cuttingMode);
			}

			// 加工方式及薄化前后厚度
			String processingModeAndThickness = ob.getString("processingModeAndThickness");

			if (!isNullOrEmpty(processingModeAndThickness)) {
				ibamap.put("processingModeAndThickness", processingModeAndThickness);
			}

			// 集成度（格式如：60PANEL）:
			String Integration = ob.getString("Integration");

			if (!isNullOrEmpty(Integration)) {
				ibamap.put("Integration", Integration);
			}

			// 成品型号
			String finishedGoodType = ob.getString("finishedGoodType");
			if (!isNullOrEmpty(finishedGoodType)) {
				ibamap.put("finishedGoodType", finishedGoodType);
			}

			//String partnumber = DBUtil.getNextValue("WTPARTID_seq", 10);

			//String partname = DBUtil.getNextValue("variantnameseq", 10);

			// 创建为成品： 否
			//part.setEndItem(false);
			/*
			 * if ("否".equals(endItem)) { part.setEndItem(false); } else if
			 * ("是".equals(endItem)) { part.setEndItem(true); }
			 */
			// 源 制造，购买，外协加工、虚拟件 make/buy/SUBCONTRACTOR/PHANTOM

			Source sourcess = Source.toSource("make");
			if (!isNullOrEmpty(source)) {
				if ("制造".equals(source)) {
					sourcess = Source.toSource("make");
				} else if ("购买".equals(source)) {
					sourcess = Source.toSource("buy");
				} else if ("外协加工".equals(source)) {
					sourcess = Source.toSource("SUBCONTRACTOR");
				} else if ("虚拟件".equals(source)) {
					sourcess = Source.toSource("PHANTOM");
				}

			}
			//part.setSource(sourcess);

			ViewReference viewRef = null;
			View viewview = ViewHelper.service.getView("Design");
			viewRef = ViewReference.newViewReference(viewview);

			//part.setView(viewRef);

			//IBAUtil.setSoftTypeIBAValues(part, ibamap);
			// 设置分类
			//ClassificationUtil.setClassification("wt.part.WTPart", SemiFinishedGoodType, part);
			// 设置分类属性 用于设置不在本次配套申请的编码
			setClassificationATT(classificationATT, SemiFinishedGoodType, part);

			// CreateNewPartFormProcessor.updateSemiFinishedGoodInfo
			CreateNewPartFormUtil.updateSemiFinishedGoodInfo(part);
			
			IBAUtil.forceSetIBAValues(part, ibamap);
			/*
			 * if (!isNullOrEmpty(synchysis)) { //ibamap.put("synchysis",
			 * synchysis); log.info("=====synchysis 22222:"
			 * +synchysis); CSCIBA.setIBAStringValue(part, "synchysis",
			 * synchysis); }
			 */
			log.info("===editSemiFinishedGood end:" + part.getNumber());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return part;
	}

	/**
	 * 设置分类属性值
	 * 
	 * @param classificationATT
	 * @param SemiFinishedGoodType
	 * @param part
	 */
	public static void setClassificationATT(String classificationATT, String SemiFinishedGoodType, WTPart part) {
		// 分类与分类属性为空时 return 否则设置分类属性
		if (isNullOrEmpty(classificationATT) || isNullOrEmpty(SemiFinishedGoodType)) {
			return;
		}
		try {
			part = GenericUtil.getPart(part.getNumber(), "");
			String classtype = (String) LWCUtil.getValue(part, "SemiFinishedGoodType");
			if ("C1".equalsIgnoreCase(classtype)) {
				log.info("==C1 classificationATT:"+classificationATT);
				// 对应CF料号and MtlNumofCF
				// 对应LC料号and MtlNumofLC
				// 对应TFT料号 MtlNumofTFT
				String[] atts = classificationATT.split(split_flag);
				log.info("==C1 atts:"+atts.length);
				//第一位：对应CF料号   第二位：对应LC料号 第三位：对应TFT料号
				if(atts.length!=0){
					if(atts.length==1){
						//CSCIBA.setIBAStringValue(part, "MtlNumofCF", atts[0]);
						LWCUtil.setStringIBAValue(part, "MtlNumofCF", atts[0]);
					}else if(atts.length==2){
						//CSCIBA.setIBAStringValue(part, "MtlNumofCF", atts[0]);
						//CSCIBA.setIBAStringValue(part, "MtlNumofLC", atts[1]);
						LWCUtil.setStringIBAValue(part, "MtlNumofCF", atts[0]);
						LWCUtil.setStringIBAValue(part, "MtlNumofLC", atts[1]);
					}else if(atts.length==3){
						//CSCIBA.setIBAStringValue(part, "MtlNumofCF", atts[0]);
						//CSCIBA.setIBAStringValue(part, "MtlNumofLC", atts[1]);
						//CSCIBA.setIBAStringValue(part, "MtlNumofTFT", atts[2]);
						
						LWCUtil.setStringIBAValue(part, "MtlNumofCF", atts[0]);
						LWCUtil.setStringIBAValue(part, "MtlNumofLC", atts[1]);
						LWCUtil.setStringIBAValue(part, "MtlNumofTFT", atts[2]);
					}
				}
				
				
				
			} else if ("C2".equalsIgnoreCase(classtype)) {
				// 对应C1料号 MtlNumofC1C2
				LWCUtil.setStringIBAValue(part, "C1MtlNum", classificationATT);
			} else if ("C3".equalsIgnoreCase(classtype)) {
				LWCUtil.setStringIBAValue(part, "MtlNumofC1C2", classificationATT);
			} else if ("C5".equalsIgnoreCase(classtype)) {
				// 对应C2料号 C2MtlNum
				LWCUtil.setStringIBAValue(part, "C2MtlNum", classificationATT);
			} else if ("C6".equalsIgnoreCase(classtype)) {
				// MtlNumofC5C7
				// 对应C5 or C7 or
				// TM料号,优先C7，无C7，对应C5，如果无C5或C7，申请人直接写入TM，则流程通过后，无需再写入C5或C7的值
				LWCUtil.setStringIBAValue(part, "MtlNumofC5C7", classificationATT);
			} else if ("C7".equalsIgnoreCase(classtype)) {
				// 对应C2 or C5 or C8 or
				// TM料号,优先C7，无C5，对应C8，如果无C8或C5，，对应C2，申请人直接写入TM，则流程通过后，无需再写入C2 或
				// C5 或 C8的值
				// C2C5MtlNum
				CSCIBA.setIBAStringValue(part, "C2C5MtlNum", classificationATT);

			} else if ("C8".equalsIgnoreCase(classtype)) {
				// 对应C1料号（针对外购武汉F8时，请填写对应的CF料号、LC料号、TFT料号）
				LWCUtil.setStringIBAValue(part, "C1MtlNum", classificationATT);
			} else if ("C9".equalsIgnoreCase(classtype)) {
				// 对应C1料号
				LWCUtil.setStringIBAValue(part, "C1MtlNum", classificationATT);
			} else if ("L1".equalsIgnoreCase(classtype)) {
				// 对应玻璃料号
				// MtlNumofL1
				//CSCIBA.setIBAStringValue(part, "MtlNumofGLASS", classificationATT);
				LWCUtil.setStringIBAValue(part, "MtlNumofGLASS", classificationATT);
				//classificationATT = (String) LWCUtil.getValue(part, "cn.tianma.MtlNumofGLASS");
			}else if ("L2".equalsIgnoreCase(classtype)) {
				// 对应L1料号
				// MtlNumofL1
				LWCUtil.setStringIBAValue(part, "MtlNumofL1", classificationATT);
			} else if ("L3".equalsIgnoreCase(classtype)) {
				// 对应玻璃料号
				// MtlNumofL1
				//CSCIBA.setIBAStringValue(part, "MtlNumofGLASS", classificationATT);
				LWCUtil.setStringIBAValue(part, "MtlNumofGLASS", classificationATT);
			} else if ("L4".equalsIgnoreCase(classtype)) {
				// 对应L3料号 NewMtlNumofL3
				LWCUtil.setStringIBAValue(part, "NewMtlNumofL3", classificationATT);
			}  else if ("S3".equalsIgnoreCase(classtype)) {
				// 对应S1料号	cn.tianma.MtlNumofS1
				LWCUtil.setStringIBAValue(part, "MtlNumofS1", classificationATT);
			}else if ("S4".equalsIgnoreCase(classtype)) {
				// 对应S3料号 MtlNumofS3
				LWCUtil.setStringIBAValue(part, "MtlNumofS3", classificationATT);
			} else if ("E1".equalsIgnoreCase(classtype)) {
				// 对应A4 or A5 or A6 NewMtlNumofA4A5
				LWCUtil.setStringIBAValue(part, "NewMtlNumofA4A5", classificationATT);
			} else if ("E2".equalsIgnoreCase(classtype)) {
				// 对应A4 or A5 or A6 and POL料号 NewMtlNumofA4A5POL
				LWCUtil.setStringIBAValue(part, "NewMtlNumofA4A5POL", classificationATT);
			} else if ("E3".equalsIgnoreCase(classtype)) {
				// 对应A1 or A2 or A3 MtlNumofA1A2A3
				//CSCIBA.setIBAStringValue(part, "MtlNumofA1A2A3", classificationATT);
				LWCUtil.setStringIBAValue(part, "MtlNumofA1A2A3", classificationATT);
			} else if ("E4".equals(classtype)) {
				// 对应(A1 or A2 or A3 or E5) and POL,优先对应E5
				// NewMtlNumofA1A2A3E5POL
				LWCUtil.setStringIBAValue(part, "NewMtlNumofA1A2A3E5POL", classificationATT);
			} else if ("E5".equals(classtype)) {
				// 对应A1 or A2 or A3 MtlNumofA1A2A3
				LWCUtil.setStringIBAValue(part, "MtlNumofA1A2A3", classificationATT);
			} else if ("E6".equals(classtype)) {
				// 对应E5 or E7 cn.tianma.MtlNumofA1A2A3E5
				//CSCIBA.setIBAStringValue(part, "MtlNumofA1A2A3E5", classificationATT);
				LWCUtil.setStringIBAValue(part, "cn.tianma.MtlNumofA1A2A3E5", classificationATT);

			} else if ("E7".equals(classtype)) {
				// 对应E5 cn.tianma.MtlNumofA1A2A3E5
				//CSCIBA.setIBAStringValue(part, "MtlNumofA1A2A3E5", classificationATT);
				LWCUtil.setStringIBAValue(part, "cn.tianma.MtlNumofA1A2A3E5", classificationATT);

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取分类属性值
	 * 
	 * @param classificationATT
	 * @param SemiFinishedGoodType
	 * @param part
	 */
	public static String getClassificationATT(WTPart part) {
		String classificationATT = "";
		try {
			// part = GenericUtil.getPart(part.getNumber(), "");
			String classtype = (String) LWCUtil.getValue(part, "SemiFinishedGoodType");
			if ("C1".equalsIgnoreCase(classtype)) {
				// 对应CF料号and MtlNumofCF
				// 对应LC料号and MtlNumofLC
				// 对应TFT料号 MtlNumofTFT
				classificationATT = (String) LWCUtil.getValue(part, "MtlNumofCF");
			} else if ("C2".equalsIgnoreCase(classtype)) {
				// 对应C1料号 MtlNumofC1C2
				classificationATT = (String) LWCUtil.getValue(part, "C1MtlNum");
			} else if ("C3".equalsIgnoreCase(classtype)) {
				classificationATT = (String) LWCUtil.getValue(part, "MtlNumofC1C2");
			} else if ("C5".equalsIgnoreCase(classtype)) {
				// 对应C2料号 C2MtlNum
				classificationATT = (String) LWCUtil.getValue(part, "C2MtlNum");

			} else if ("C6".equalsIgnoreCase(classtype)) {
				// MtlNumofC5C7
				// 对应C5 or C7 or
				// TM料号,优先C7，无C7，对应C5，如果无C5或C7，申请人直接写入TM，则流程通过后，无需再写入C5或C7的值
				classificationATT = (String) LWCUtil.getValue(part, "MtlNumofC5C7");
			} else if ("C7".equalsIgnoreCase(classtype)) {
				// 对应C2 or C5 or C8 or
				// TM料号,优先C7，无C5，对应C8，如果无C8或C5，，对应C2，申请人直接写入TM，则流程通过后，无需再写入C2 或
				// C5 或 C8的值
				// C2C5MtlNum
				classificationATT = (String) LWCUtil.getValue(part, "C2C5MtlNum");

			} else if ("C8".equalsIgnoreCase(classtype)) {
				// 对应C1料号（针对外购武汉F8时，请填写对应的CF料号、LC料号、TFT料号）
				classificationATT = (String) LWCUtil.getValue(part, "C1MtlNum");

			} else if ("C9".equalsIgnoreCase(classtype)) {
				// 对应C1料号
				classificationATT = (String) LWCUtil.getValue(part, "C1MtlNum");

			} else if ("L2".equalsIgnoreCase(classtype)) {
				// 对应L1料号
				// MtlNumofL1
				classificationATT = (String) LWCUtil.getValue(part, "MtlNumofL1");

			} else if ("L4".equalsIgnoreCase(classtype)) {
				// 对应L3料号 NewMtlNumofL3
				classificationATT = (String) LWCUtil.getValue(part, "NewMtlNumofL3");

			} else if ("S4".equalsIgnoreCase(classtype)) {
				// 对应S3料号 MtlNumofS3
				classificationATT = (String) LWCUtil.getValue(part, "MtlNumofS3");

			} else if ("E1".equalsIgnoreCase(classtype)) {
				// 对应A4 or A5 or A6 NewMtlNumofA4A5
				classificationATT = (String) LWCUtil.getValue(part, "NewMtlNumofA4A5");

			} else if ("E2".equalsIgnoreCase(classtype)) {
				// 对应A4 or A5 or A6 and POL料号 NewMtlNumofA4A5POL
				classificationATT = (String) LWCUtil.getValue(part, "NewMtlNumofA4A5POL");

			} else if ("E3".equalsIgnoreCase(classtype)) {
				// 对应A1 or A2 or A3 MtlNumofA1A2A3
				classificationATT = (String) LWCUtil.getValue(part, "MtlNumofA1A2A3");

			} else if ("E4".equals(classtype)) {
				// 对应(A1 or A2 or A3 or E5) and POL,优先对应E5
				// NewMtlNumofA1A2A3E5POL
				classificationATT = (String) LWCUtil.getValue(part, "NewMtlNumofA1A2A3E5POL");

			} else if ("E5".equals(classtype)) {
				// 对应A1 or A2 or A3 MtlNumofA1A2A3
				classificationATT = (String) LWCUtil.getValue(part, "MtlNumofA1A2A3");

			} else if ("E6".equals(classtype)) {
				// 对应E5 or E7 cn.tianma.MtlNumofA1A2A3E5
				classificationATT = (String) LWCUtil.getValue(part, "cn.tianma.MtlNumofA1A2A3E5");

			} else if ("E7".equals(classtype)) {
				// 对应E5 cn.tianma.MtlNumofA1A2A3E5
				classificationATT = (String) LWCUtil.getValue(part, "cn.tianma.MtlNumofA1A2A3E5");

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return classificationATT;
	}

	/**
	 * 创建原材料
	 * 
	 * 偏光片
	 * 
	 * @param ob
	 */
	public static WTPart createMaterial(JSONObject ob) {
		WTPart part = null;
		Hashtable<String, String> ibamap = new Hashtable<String, String>();
		String softtype = softype_RawMaterial;
		try {
			// String type = ob.getString("type");

			// 通用属性:
			// 存储库：物料库
			// String containerName = ob.getString("containerName");
			// 创建为成品： 否
			// String endItem = ob.getString("endItem");
			// 视图：Design
			// String view = ob.getString("view");
			// 分类：否
			// String classification = "";
			// if(ob.has("classification")){
			// classification = ob.getString("classification");
			// }

			// 虚拟偏光片 MtlNumofPOLTop:对应上POL料号:
			String MtlNumofPOLTop = "";

			// 虚拟偏光片 MtlNumofPOLBtn:对应下POL料号
			String MtlNumofPOLBtn = "";

			// 虚拟偏光片 POLResolution:分辨率（长×宽）:
			String POLResolution = "";

			// 虚拟偏光片 DisplayMode:显示模式:
			String DisplayMode = "";

			// 虚拟偏光片 partDrawingNumber
			// 上/下偏光片料号（格式例如：上偏：1040008530，下偏：1040008540）:
			String partDrawingNumber = "";

			// 上下偏光片 isBothNewPolarizer:上下偏光片是否均为新增(务必确认上下偏一同申请还是仅单侧申请):
			String isBothNewPolarizer = "";

			// 上下偏光片 partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
			String partRecognize = "";

			// MtlNumofPOLBtn:对应下POL料号(若已有料号，务必填写正确，涉及关联mark):
			MtlNumofPOLBtn = "";

			// MtlNumofPOLTop:对应上POL料号(若已有料号，务必填写正确，涉及关联mark):
			MtlNumofPOLTop = "";

			// 类型 上、下偏光片、虚拟偏光件
			String type = ob.getString("createType");
			if (!isNullOrEmpty(type)) {
				if ("上偏光片".equals(type)) {
					softtype = softype_TopPolarizer;

					if (ob.has("MtlNumofPOLBtn")) {
						MtlNumofPOLBtn = ob.getString("MtlNumofPOLBtn");
					}
					if (!isNullOrEmpty(MtlNumofPOLBtn)) {
						ibamap.put("MtlNumofPOLBtn", MtlNumofPOLBtn);
					}
					// isBothNewPolarizer:上下偏光片是否均为新增(务必确认上下偏一同申请还是仅单侧申请):
					if (ob.has("isBothNewPolarizer")) {
						isBothNewPolarizer = ob.getString("isBothNewPolarizer");
					}

					if (!isNullOrEmpty(isBothNewPolarizer)) {
						ibamap.put("isBothNewPolarizer", isBothNewPolarizer);
					}
					// partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
					if (ob.has("partRecognize")) {
						partRecognize = ob.getString("partRecognize");
					}

					if (!isNullOrEmpty(partRecognize)) {
						ibamap.put("partRecognize", partRecognize);
					}
					// 材料型号/图纸编号:
					if (ob.has("partDrawingNumber")) {
						partDrawingNumber = ob.getString("partDrawingNumber");
					}
					if (!isNullOrEmpty(partDrawingNumber)) {
						ibamap.put("partDrawingNumber", partDrawingNumber);
					}
				} else if ("下偏光片".equals(type)) {
					softtype = softype_BotPolarizer;

					if (ob.has("MtlNumofPOLTop")) {
						MtlNumofPOLTop = ob.getString("MtlNumofPOLTop");
					}

					if (!isNullOrEmpty(MtlNumofPOLTop)) {
						ibamap.put("MtlNumofPOLTop", MtlNumofPOLTop);
					}

					// isBothNewPolarizer:上下偏光片是否均为新增(务必确认上下偏一同申请还是仅单侧申请):
					if (ob.has("isBothNewPolarizer")) {
						isBothNewPolarizer = ob.getString("isBothNewPolarizer");
					}

					if (!isNullOrEmpty(isBothNewPolarizer)) {
						ibamap.put("isBothNewPolarizer", isBothNewPolarizer);
					}
					// partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
					if (ob.has("partRecognize")) {
						partRecognize = ob.getString("partRecognize");
					}

					if (!isNullOrEmpty(partRecognize)) {
						ibamap.put("partRecognize", partRecognize);
					}
					// 材料型号/图纸编号:
					if (ob.has("partDrawingNumber")) {
						partDrawingNumber = ob.getString("partDrawingNumber");
					}
					if (!isNullOrEmpty(partDrawingNumber)) {
						ibamap.put("partDrawingNumber", partDrawingNumber);
					}

					if (!isNullOrEmpty(partDrawingNumber)) {
						ibamap.put("partDrawingNumber", partDrawingNumber);
					}
				} else if ("虚拟偏光片组件".equals(type)) {
					softtype = softype_PhantomPolarizer;
					// 对应下POL料号
					if (ob.has("MtlNumofPOLBtn1")) {
						MtlNumofPOLBtn = ob.getString("MtlNumofPOLBtn1");
					}
					if (!isNullOrEmpty(MtlNumofPOLBtn)) {
						ibamap.put("MtlNumofPOLBtn", MtlNumofPOLBtn);
					}
					// 对应上POL料号
					if (ob.has("MtlNumofPOLTop1")) {
						MtlNumofPOLTop = ob.getString("MtlNumofPOLTop1");
					}
					if (!isNullOrEmpty(MtlNumofPOLTop)) {
						ibamap.put("MtlNumofPOLTop", MtlNumofPOLTop);
					}
					// 分辨率（长×宽）
					if (ob.has("POLResolution")) {
						POLResolution = ob.getString("POLResolution");
					}
					if (!isNullOrEmpty(POLResolution)) {
						ibamap.put("POLResolution", POLResolution);
					}
					// 显示模式:
					if (ob.has("DisplayMode")) {
						DisplayMode = ob.getString("DisplayMode");
					}
					if (!isNullOrEmpty(DisplayMode)) {
						ibamap.put("DisplayMode", DisplayMode);
					}
					// partDrawingNumber
					// 上/下偏光片料号（格式例如：上偏：1040008530，下偏：1040008540）:
					if (ob.has("partDrawingNumber1")) {
						partDrawingNumber = ob.getString("partDrawingNumber1");
					}
					if (!isNullOrEmpty(partDrawingNumber)) {
						ibamap.put("partDrawingNumber", partDrawingNumber);
					}
					// partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
					if (ob.has("partRecognize")) {
						partRecognize = ob.getString("partRecognize");
					}

					if (!isNullOrEmpty(partRecognize)) {
						ibamap.put("partRecognize", partRecognize);
					}
				}
			}

			// 申请人及申请原因:
			String partApplicationReason = ob.getString("partApplicationReason");

			if (!isNullOrEmpty(partApplicationReason)) {
				ibamap.put("partApplicationReason", partApplicationReason);
			}
			// 环保类别
			String partEnvProtectionCategory = ob.getString("partEnvProtectionCategory");

			if (!isNullOrEmpty(partEnvProtectionCategory)) {
				ibamap.put("partEnvProtectionCategory", partEnvProtectionCategory);
			}
			// 检验标准
			String partInspectionStandard = ob.getString("partInspectionStandard");

			if (!isNullOrEmpty(partInspectionStandard)) {
				ibamap.put("partInspectionStandard", partInspectionStandard);
			}
			
			// 料号生效产地
			String partNumberEffectiveSite = ob.getString("partNumberEffectiveSite");
			log.info("======Materials partNumberEffectiveSite 1:"+partNumberEffectiveSite);
			if (!isNullOrEmpty(partNumberEffectiveSite)) {
				if (partNumberEffectiveSite.indexOf("（") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("（"));
				} else if (partNumberEffectiveSite.indexOf("(") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("("));
				}
				log.info("======Materials partNumberEffectiveSite 2:"+partNumberEffectiveSite);
				ibamap.put("partNumberEffectiveSite", partNumberEffectiveSite.trim());
			}
			// 产品型号
			String finishedGoodType = ob.getString("finishedGoodType");

			if (!isNullOrEmpty(finishedGoodType)) {
				ibamap.put("finishedGoodType", finishedGoodType);
			}

			// 供应商
			String partSupplier = ob.getString("partSupplier");

			if (!isNullOrEmpty(partSupplier)) {
				//key 显示名称  value 内部值
				String value = "";
				Map<String,String> map = EnumerationUtil.getEnumerationValues2("供应商名称");
				if(map.containsKey(partSupplier)){
					value = map.get(partSupplier);
				}
				if(!isNullOrEmpty(value)){
					ibamap.put("partSupplier", value);
				}else{
					ibamap.put("partSupplier", partSupplier);
				}
				//ibamap.put("partSupplier", partSupplier);
			}
			// 备注说明：
			String partNote = ob.getString("partNote");

			if (!isNullOrEmpty(partNote)) {
				ibamap.put("partNote", partNote);
			}
			// RFQ编号（深圳用）
			String partRFQNumber = ob.getString("partRFQNumber");

			if (!isNullOrEmpty(partRFQNumber)) {
				ibamap.put("partRFQNumber", partRFQNumber);
			}
			// 是否专显: 是、否
			String specialMonitor = ob.getString("specialMonitor");

			if (!isNullOrEmpty(specialMonitor)) {
				ibamap.put("specialMonitor", specialMonitor);
			}
			// 物料分级
			String materialClassification = ob.getString("materialClassification");

			if (!isNullOrEmpty(materialClassification)) {
				ibamap.put("materialClassification", materialClassification);
			}
			// 尺寸(模组尺寸，例如：5.13、4.30等):
			String partSize = ob.getString("partSize");

			if (!isNullOrEmpty(partSize)) {
				ibamap.put("partSize", partSize);
			}

			// 专用属性：
			// 类型
			// String createType = ob.getString("createType");

			/*
			 * 编号：自动生成
			 * 
			 * key:number
			 * 
			 * 名称：自动生成
			 * 
			 * key:name
			 */

			// 源：制造，购买，外协加工、虚拟件
			String source = ob.getString("source");
			// 默认单位
			String defaultUnit = ob.getString("defaultUnit");
			QuantityUnit qunit = null;
			if (!isNullOrEmpty(defaultUnit)) {
				qunit = QuantityUnit.toQuantityUnit(defaultUnit);
			}

			// 物料中文名称
			String partCName = ob.getString("partCName");

			if (!isNullOrEmpty(partCName)) {
				ibamap.put("partCName", partCName);
			}

			// 主要规格（长×宽×厚mm）

			String partMainSpecification = ob.getString("partMainSpecification");

			if (!isNullOrEmpty(partMainSpecification)) {
				ibamap.put("partMainSpecification", partMainSpecification);
			}
			// 吸收轴角度(与长边逆时针方向夹角，注：长边为靠近source IC侧的边)：

			String absorptionShaftAngle = ob.getString("absorptionShaftAngle");

			if (!isNullOrEmpty(absorptionShaftAngle)) {
				ibamap.put("absorptionShaftAngle", absorptionShaftAngle);
			}
			// 偏光片类型
			String polarizerType = ob.getString("polarizerType");

			if (!isNullOrEmpty(polarizerType)) {
				ibamap.put("polarizerType", polarizerType);
			}

			// 表面处理方式：
			String surfaceTreatment = ob.getString("surfaceTreatment");

			if (!isNullOrEmpty(surfaceTreatment)) {
				ibamap.put("surfaceTreatment", surfaceTreatment);
			}
			// 是否需要零件承认（POL、背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）: 是 、否
			/*
			 * String partRecognize = ob.getString("partRecognize");
			 * 
			 * if (!isNullOrEmpty(partRecognize)) { ibamap.put("partRecognize",
			 * partRecognize); }
			 */

			// String source = ob.getString("source");
			String partnumber = DBUtil.getNextValue("WTPARTID_seq", 10);

			String partname = DBUtil.getNextValue("variantnameseq", 10);

			WTContainer repcon = getContainerByName(partContainerName);
			part = WTPart.newWTPart();
			TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference(softtype);
			part.setTypeDefinitionReference(typeDefinitionRef);
			part.setNumber(partnumber);
			part.setContainer(repcon);
			part.setOrganization(repcon.getContainer().getOrganization());
			part.setName(partname);

			part.setOrganization(repcon.getContainer().getOrganization());
			part.setName(partname);
			if (qunit != null) {
				part.setDefaultUnit(qunit);
			}

			// 创建为成品： 否
			part.setEndItem(false);
			/*
			 * if ("否".equals(endItem)) { part.setEndItem(false); } else if
			 * ("是".equals(endItem)) { part.setEndItem(true); }
			 */
			// 源 制造，购买，外协加工、虚拟件 make/buy/SUBCONTRACTOR/PHANTOM
			Source sourcess = Source.toSource("make");
			if (!isNullOrEmpty(source)) {
				if (source.equals("制造")) {
					sourcess = Source.toSource("make");
				} else if (source.equals("购买")) {
					sourcess = Source.toSource("buy");
				} else if (source.equals("外协加工")) {
					sourcess = Source.toSource("SUBCONTRACTOR");
				} else if (source.equals("虚拟件")) {
					sourcess = Source.toSource("PHANTOM");
				}

			}
			part.setSource(sourcess);

			ViewReference viewRef = null;
			View viewview = ViewHelper.service.getView("Design");
			viewRef = ViewReference.newViewReference(viewview);

			part.setView(viewRef);

			part = (WTPart) PersistenceHelper.manager.save(part);
			//终止原编码流程
			//WfEngineHelper.service.terminateObjectsRunningWorkflows(part);
			//end
			part = (WTPart) LifeCycleHelper.service.setLifeCycleState(part, State.INWORK);
			IBAUtil.setSoftTypeIBAValues(part, ibamap);

			// 更新原材料物料属性 设置名称 及默认单位
			CreateNewPartFormProcessor.updateRawMaterialInfo(part);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return part;
	}
	
	/**
	 * 编辑原材料
	 * 
	 * 偏光片
	 * 
	 * @param ob
	 */
	public static WTPart editMaterial(JSONObject ob) {
		WTPart part = null;
		Hashtable<String, String> ibamap = new Hashtable<String, String>();
		String softtype = softype_RawMaterial;
		try {
			if(ob.has("number")){
				String partnumber = ob.getString("number");
				part = GenericUtil.getPart(partnumber, "", "Design");
			}
			if(part == null){
				return part;
			}
			// 虚拟偏光片 MtlNumofPOLTop:对应上POL料号:
			String MtlNumofPOLTop = "";

			// 虚拟偏光片 MtlNumofPOLBtn:对应下POL料号
			String MtlNumofPOLBtn = "";

			// 虚拟偏光片 POLResolution:分辨率（长×宽）:
			String POLResolution = "";

			// 虚拟偏光片 DisplayMode:显示模式:
			String DisplayMode = "";

			// 虚拟偏光片 partDrawingNumber
			// 上/下偏光片料号（格式例如：上偏：1040008530，下偏：1040008540）:
			String partDrawingNumber = "";

			// 上下偏光片 isBothNewPolarizer:上下偏光片是否均为新增(务必确认上下偏一同申请还是仅单侧申请):
			String isBothNewPolarizer = "";

			// 上下偏光片 partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
			String partRecognize = "";

			// MtlNumofPOLBtn:对应下POL料号(若已有料号，务必填写正确，涉及关联mark):
			MtlNumofPOLBtn = "";

			// MtlNumofPOLTop:对应上POL料号(若已有料号，务必填写正确，涉及关联mark):
			MtlNumofPOLTop = "";

			// 类型 上、下偏光片、虚拟偏光件
			String type = ob.getString("createType");
			if (!isNullOrEmpty(type)) {
				if ("上偏光片".equals(type)) {
					softtype = softype_TopPolarizer;

					if (ob.has("MtlNumofPOLBtn")) {
						MtlNumofPOLBtn = ob.getString("MtlNumofPOLBtn");
					}
					if (!isNullOrEmpty(MtlNumofPOLBtn)) {
						ibamap.put("MtlNumofPOLBtn", MtlNumofPOLBtn);
					}
					// isBothNewPolarizer:上下偏光片是否均为新增(务必确认上下偏一同申请还是仅单侧申请):
					if (ob.has("isBothNewPolarizer")) {
						isBothNewPolarizer = ob.getString("isBothNewPolarizer");
					}

					if (!isNullOrEmpty(isBothNewPolarizer)) {
						ibamap.put("isBothNewPolarizer", isBothNewPolarizer);
					}
					// partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
					if (ob.has("partRecognize")) {
						partRecognize = ob.getString("partRecognize");
					}
					log.info("===top partRecognize:"+partRecognize);

					if (!isNullOrEmpty(partRecognize)) {
						ibamap.put("partRecognize", partRecognize);
					}
					// 材料型号/图纸编号:
					if (ob.has("partDrawingNumber")) {
						partDrawingNumber = ob.getString("partDrawingNumber");
					}
					log.info("===top partDrawingNumber:"+partDrawingNumber);
					if (!isNullOrEmpty(partDrawingNumber)) {
						ibamap.put("partDrawingNumber", partDrawingNumber);
					}
				} else if ("下偏光片".equals(type)) {
					softtype = softype_BotPolarizer;

					if (ob.has("MtlNumofPOLTop")) {
						MtlNumofPOLTop = ob.getString("MtlNumofPOLTop");
					}

					if (!isNullOrEmpty(MtlNumofPOLTop)) {
						ibamap.put("MtlNumofPOLTop", MtlNumofPOLTop);
					}

					// isBothNewPolarizer:上下偏光片是否均为新增(务必确认上下偏一同申请还是仅单侧申请):
					if (ob.has("isBothNewPolarizer")) {
						isBothNewPolarizer = ob.getString("isBothNewPolarizer");
					}

					if (!isNullOrEmpty(isBothNewPolarizer)) {
						ibamap.put("isBothNewPolarizer", isBothNewPolarizer);
					}
					// partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
					if (ob.has("partRecognize")) {
						partRecognize = ob.getString("partRecognize");
					}
					log.info("===bottom partRecognize:"+partRecognize);

					if (!isNullOrEmpty(partRecognize)) {
						ibamap.put("partRecognize", partRecognize);
					}
					// 材料型号/图纸编号:
					if (ob.has("partDrawingNumber")) {
						partDrawingNumber = ob.getString("partDrawingNumber");
					}
					log.info("===bottom partDrawingNumber:"+partDrawingNumber);

					if (!isNullOrEmpty(partDrawingNumber)) {
						ibamap.put("partDrawingNumber", partDrawingNumber);
					}

				} else if ("虚拟偏光片组件".equals(type)) {
					softtype = softype_PhantomPolarizer;
					// 对应下POL料号
					if (ob.has("MtlNumofPOLBtn1")) {
						MtlNumofPOLBtn = ob.getString("MtlNumofPOLBtn1");
					}
					if (!isNullOrEmpty(MtlNumofPOLBtn)) {
						ibamap.put("MtlNumofPOLBtn", MtlNumofPOLBtn);
					}
					// 对应上POL料号
					if (ob.has("MtlNumofPOLTop1")) {
						MtlNumofPOLTop = ob.getString("MtlNumofPOLTop1");
					}
					if (!isNullOrEmpty(MtlNumofPOLTop)) {
						ibamap.put("MtlNumofPOLTop", MtlNumofPOLTop);
					}
					// 分辨率（长×宽）
					if (ob.has("POLResolution")) {
						POLResolution = ob.getString("POLResolution");
					}
					if (!isNullOrEmpty(POLResolution)) {
						ibamap.put("POLResolution", POLResolution);
					}
					// 显示模式:
					if (ob.has("DisplayMode")) {
						DisplayMode = ob.getString("DisplayMode");
					}
					if (!isNullOrEmpty(DisplayMode)) {
						ibamap.put("DisplayMode", DisplayMode);
					}
					// partDrawingNumber
					// 上/下偏光片料号（格式例如：上偏：1040008530，下偏：1040008540）:
					if (ob.has("partDrawingNumber1")) {
						partDrawingNumber = ob.getString("partDrawingNumber1");
					}
					log.info("===xuni partDrawingNumber:"+partDrawingNumber);

					if (!isNullOrEmpty(partDrawingNumber)) {
						ibamap.put("partDrawingNumber", partDrawingNumber);
					}
					// partRecognize:是否需要零件承认（背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）:
					if (ob.has("partRecognize")) {
						partRecognize = ob.getString("partRecognize");
					}
					log.info("===xuni partRecognize:"+partRecognize);

					if (!isNullOrEmpty(partRecognize)) {
						ibamap.put("partRecognize", partRecognize);
					}
				}
			}
			log.info("=== partRecognize:"+partRecognize);
			log.info("=== partDrawingNumber:"+partDrawingNumber);

			// 申请人及申请原因:
			String partApplicationReason = ob.getString("partApplicationReason");

			if (!isNullOrEmpty(partApplicationReason)) {
				ibamap.put("partApplicationReason", partApplicationReason);
			}
			// 环保类别
			String partEnvProtectionCategory = ob.getString("partEnvProtectionCategory");

			if (!isNullOrEmpty(partEnvProtectionCategory)) {
				ibamap.put("partEnvProtectionCategory", partEnvProtectionCategory);
			}
			// 检验标准
			String partInspectionStandard = ob.getString("partInspectionStandard");

			if (!isNullOrEmpty(partInspectionStandard)) {
				ibamap.put("partInspectionStandard", partInspectionStandard);
			}

			// 料号生效产地
			String partNumberEffectiveSite = ob.getString("partNumberEffectiveSite");
			log.info("======Materials partNumberEffectiveSite 1:"+partNumberEffectiveSite);
			if (!isNullOrEmpty(partNumberEffectiveSite)) {
				if (partNumberEffectiveSite.indexOf("（") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("（"));
				} else if (partNumberEffectiveSite.indexOf("(") != -1) {
					partNumberEffectiveSite = partNumberEffectiveSite.substring(0,
							partNumberEffectiveSite.indexOf("("));
				}
				log.info("======Materials partNumberEffectiveSite 2:"+partNumberEffectiveSite);
				ibamap.put("partNumberEffectiveSite", partNumberEffectiveSite.trim());
			}
			// 产品型号
			String finishedGoodType = ob.getString("finishedGoodType");

			if (!isNullOrEmpty(finishedGoodType)) {
				ibamap.put("finishedGoodType", finishedGoodType);
			}

			// 供应商
			String partSupplier = ob.getString("partSupplier");

			if (!isNullOrEmpty(partSupplier)) {
				//ibamap.put("partSupplier", partSupplier);
				//key 显示名称  value 内部值
				String value = "";
				Map<String,String> map = EnumerationUtil.getEnumerationValues2("供应商名称");
				if(map.containsKey(partSupplier)){
					value = map.get(partSupplier);
				}
				if(!isNullOrEmpty(value)){
					ibamap.put("partSupplier", value);
				}else{
					ibamap.put("partSupplier", partSupplier);
				}
			}
			// 备注说明：
			String partNote = ob.getString("partNote");

			if (!isNullOrEmpty(partNote)) {
				ibamap.put("partNote", partNote);
			}
			// RFQ编号（深圳用）
			String partRFQNumber = ob.getString("partRFQNumber");

			if (!isNullOrEmpty(partRFQNumber)) {
				ibamap.put("partRFQNumber", partRFQNumber);
			}
			// 是否专显: 是、否
			String specialMonitor = ob.getString("specialMonitor");

			if (!isNullOrEmpty(specialMonitor)) {
				ibamap.put("specialMonitor", specialMonitor);
			}
			// 物料分级
			String materialClassification = ob.getString("materialClassification");

			if (!isNullOrEmpty(materialClassification)) {
				ibamap.put("materialClassification", materialClassification);
			}
			// 尺寸(模组尺寸，例如：5.13、4.30等):
			String partSize = ob.getString("partSize");

			if (!isNullOrEmpty(partSize)) {
				ibamap.put("partSize", partSize);
			}

			// 专用属性：
			// 类型
			// String createType = ob.getString("createType");

			/*
			 * 编号：自动生成
			 * 
			 * key:number
			 * 
			 * 名称：自动生成
			 * 
			 * key:name
			 */

			// 源：制造，购买，外协加工、虚拟件
			String source = ob.getString("source");
			// 默认单位
			String defaultUnit = ob.getString("defaultUnit");
			QuantityUnit qunit = null;
			if (!isNullOrEmpty(defaultUnit)) {
				qunit = QuantityUnit.toQuantityUnit(defaultUnit);
			}

			// 物料中文名称
			String partCName = ob.getString("partCName");

			if (!isNullOrEmpty(partCName)) {
				ibamap.put("partCName", partCName);
			}

			// 主要规格（长×宽×厚mm）

			String partMainSpecification = ob.getString("partMainSpecification");

			if (!isNullOrEmpty(partMainSpecification)) {
				ibamap.put("partMainSpecification", partMainSpecification);
			}
			// 吸收轴角度(与长边逆时针方向夹角，注：长边为靠近source IC侧的边)：

			String absorptionShaftAngle = ob.getString("absorptionShaftAngle");

			if (!isNullOrEmpty(absorptionShaftAngle)) {
				ibamap.put("absorptionShaftAngle", absorptionShaftAngle);
			}
			// 偏光片类型
			String polarizerType = ob.getString("polarizerType");

			if (!isNullOrEmpty(polarizerType)) {
				ibamap.put("polarizerType", polarizerType);
			}

			// 表面处理方式：
			String surfaceTreatment = ob.getString("surfaceTreatment");

			if (!isNullOrEmpty(surfaceTreatment)) {
				ibamap.put("surfaceTreatment", surfaceTreatment);
			}
			// 是否需要零件承认（POL、背光、铁框、TP、PCB（A）、FPC（A）需要零件承认）: 是 、否
			/*
			 * String partRecognize = ob.getString("partRecognize");
			 * 
			 * if (!isNullOrEmpty(partRecognize)) { ibamap.put("partRecognize",
			 * partRecognize); }
			 */

			// String source = ob.getString("source");
			//String partnumber = DBUtil.getNextValue("WTPARTID_seq", 10);

			//String partname = DBUtil.getNextValue("variantnameseq", 10);

			/*WTContainer repcon = getContainerByName(partContainerName);
			part = WTPart.newWTPart();
			TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference(softtype);
			part.setTypeDefinitionReference(typeDefinitionRef);
			part.setNumber(partnumber);
			part.setContainer(repcon);
			part.setOrganization(repcon.getContainer().getOrganization());
			part.setName(partname);

			part.setOrganization(repcon.getContainer().getOrganization());
			part.setName(partname);
			if (qunit != null) {
				part.setDefaultUnit(qunit);
			}*/

			// 创建为成品： 否
			//part.setEndItem(false);
			/*
			 * if ("否".equals(endItem)) { part.setEndItem(false); } else if
			 * ("是".equals(endItem)) { part.setEndItem(true); }
			 */
			// 源 制造，购买，外协加工、虚拟件 make/buy/SUBCONTRACTOR/PHANTOM
			Source sourcess = Source.toSource("make");
			if (!isNullOrEmpty(source)) {
				if (source.equals("制造")) {
					sourcess = Source.toSource("make");
				} else if (source.equals("购买")) {
					sourcess = Source.toSource("buy");
				} else if (source.equals("外协加工")) {
					sourcess = Source.toSource("SUBCONTRACTOR");
				} else if (source.equals("虚拟件")) {
					sourcess = Source.toSource("PHANTOM");
				}

			}
			//part.setSource(sourcess);

			ViewReference viewRef = null;
			View viewview = ViewHelper.service.getView("Design");
			viewRef = ViewReference.newViewReference(viewview);

			//part.setView(viewRef);

			//part = (WTPart) PersistenceHelper.manager.save(part);

			//part = (WTPart) LifeCycleHelper.service.setLifeCycleState(part, State.INWORK);
			//IBAUtil.setSoftTypeIBAValues(part, ibamap);

			// 更新原材料物料属性 设置名称 及默认单位
			CreateNewPartFormProcessor.updateRawMaterialInfo(part);
			
			IBAUtil.forceSetIBAValues(part, ibamap);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.info("========edit Exception"+e);
			e.printStackTrace();
		}
		return part;
	}

	/**
	 * 根据创建类型返回相应属性默认值
	 * 
	 * @param number
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmMaterialsApplicationTypeC", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmMaterialsApplicationTypeC(@RequestParam(value = "type", required = true) String type,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		String param222 = request.getParameter("type");
		log.info("======type =========" + type);
		response.setContentType("application/json; charset=UTF-8");
		String result = "";
		/*
		 * result = firstValidate(); if (!isNullOrEmpty(result)) {
		 * out.print(result); return; }
		 */
		// 逻辑处理
		// result = searhMaterialPart(number);
		if (!isNullOrEmpty(type) && "C".equals(type)) {
			// C类
			result = TypeC();
		} else if (!isNullOrEmpty(type) && "E".equals(type)) {
			// E类
			result = TypeE();
		} else if (!isNullOrEmpty(type) && "LS".equals(type)) {
			// L&S类
			result = TypeLS();
		} else if (!isNullOrEmpty(type) && "Other".equals(type)) {
			// 偏光片及POL组件
			result = TypeOther();
		}
		out.print(result);
	}

	public static String TypeC() {
		log.info("==================MaterialsApplicationService.TypeC================");
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();

		return obj.toString();
	}

	public static String TypeE() {
		log.info("==================MaterialsApplicationService.TypeE================");
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();

		return obj.toString();
	}

	public static String TypeLS() {
		log.info("==================MaterialsApplicationService.TypeLS================");
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();

		return obj.toString();
	}

	public static String TypeOther() {
		log.info("==================MaterialsApplicationService.TypeOther================");
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();

		return obj.toString();
	}

	/**
	 * 空或者NULL值时返回true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str.equals("NULL"));
	}

	/**
	 * 根据名称获取存储库
	 */
	public static WTContainer getContainerByName(String name) throws WTException {

		QuerySpec queryspec = new QuerySpec(WTContainer.class);
		queryspec.appendWhere(new SearchCondition(WTContainer.class, WTContainer.NAME, "=", name), 0);
		QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
		if (queryresult.hasMoreElements()) {
			WTContainer container = (WTContainer) queryresult.nextElement();
			// WTContainerRef wtcontainerref1 =
			// pdmlinkproduct.getContainerReference();
			return container;
		}
		return null;

	}

	/**
	 * 获取所有成品信息
	 * 
	 * @return
	 */
	public static HashMap<String, HashMap<String, String>> getVDNMultilingual() {
		HashMap<String, HashMap<String, String>> apphm = new HashMap<String, HashMap<String, String>>();
		try {
			QuerySpec wtquer = new QuerySpec(wt.part.WTPart.class);
			TypeDefinitionReference softTypeDefRef = TypedUtilityServiceHelper.service
					.getTypeDefinitionReference("cn.tianma.FinishedGood");
			SearchCondition typeCondition = new SearchCondition(wt.part.WTPart.class,
					wt.part.WTPart.TYPE_DEFINITION_REFERENCE + ".key.branchId", SearchCondition.EQUAL,
					softTypeDefRef.getKey().getBranchId());
			wtquer.appendWhere(typeCondition);
			wtquer.appendAnd();
			wtquer.appendWhere(new SearchCondition(WTPart.class, "iterationInfo.latest", "TRUE"), 0);
			QueryResult wtquerRes = PersistenceHelper.manager.find(wtquer);
			log.info("qs:" + wtquer.toString());
			while (wtquerRes.hasMoreElements()) {
				WTPart part = (WTPart) wtquerRes.nextElement();

			}

		} catch (Exception e) {
			// e.printStackTrace();
			log.error(e.getMessage(), e);
		} finally {

		}
		return apphm;
	}

	public static void main(String[] args) throws WTException, RemoteException {
		if (!RemoteMethodServer.ServerFlag) {
			String method = "getPartByType";

			try {
				log.info("Debug   RemoteMethodServer...");
				RemoteMethodServer server = RemoteMethodServer.getDefault();
				server.setUserName("wcadmin");
				server.setPassword("tmadmin");
				log.info("...");
				RemoteMethodServer.getDefault().invoke(method, MaterialsApplicationService.class.getName(), null, null,
						null);
				log.info("Debug  end RemoteMethodServer...");
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}

		} else {
			log.info("Debug   importBoms...");
			log.info("1111======>>>");
			getVDNMultilingual();
			log.info("Debug   end importBoms...");
		}

	}

	/**
	 * 根据类型及数据创建原材料或半成品
	 * 
	 * @param number
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/test", method = { RequestMethod.POST, RequestMethod.GET })
	public void test(@RequestBody String data, HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		String datalist = request.getParameter("datalist");
		log.info("======datalist =========" + datalist);
		log.info("======data =========" + data);
		response.setContentType("text/html; charset=UTF-8");
		String result = "";
		// 逻辑处理
		JSONObject obj = new JSONObject(data);
		Iterator iter = obj.keys();
		while (iter.hasNext()) {
			String key = iter.next().toString();
			log.info("======key =========" + key + "===value:" + obj.getString(key));
		}
		out.print(data);
	}

	@RequestMapping(value = "/tmGetMaterialsClassification", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmGetMaterialsClassification(@RequestParam(value = "number", required = true) String number,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		log.info("====== tmGetMaterialsClassificationnumber =========" + number);
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String result = "";
		result = getMaterialsClassification(number);
		out.print(result);
	}
	@RequestMapping(value = "/tmGetMaterialsClassificationByName", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmGetMaterialsClassificationByName(@RequestParam(value = "name", required = true) String name,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		log.info("====== tmGetMaterialsClassificationnumber =========" + name);
		response.setContentType("text/html; charset=UTF-8");
		String result = "";
		result = getMaterialsClassificationByName(name);
		out.print(result);
	}
	/**
	 * 获取分类属性值
	 * 
	 * @param number
	 * @return
	 */
	public String getMaterialsClassification(String number) {
		JSONObject result = new JSONObject();
		String classificationATT = "";
		try {
			WTPart part = GenericUtil.getPart(number, "");
			if (part == null) {
				result.put("datalist", "");
				return result.toString();
			}
			String classtype = (String) LWCUtil.getValue(part, "SemiFinishedGoodType");
			log.info("=====getMaterialsClassification classtype:" + classtype);
			List<HashMap<String, String>>  list =  ClassificationUtil.getNodeIBAByPart2(part);
			JSONObject object = new JSONObject();
			for(HashMap<String, String> map : list ){
				String displayname = map.get("displayname");
				String value = map.get("value");
				String key = map.get("key");
				System.out.println("====displayname:"+displayname+"==key:"+key+"---value:"+value);
				object.put(displayname, value==null?"":value);
			}
			result.put("datalist", object);
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.info("===getMaterialsClassification Exception:" + e);
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * @throws Exception
	 */

	@RequestMapping(value = "/getAccessForMaterials", method = { RequestMethod.POST, RequestMethod.GET })
	public void getAccessForMaterials(HttpServletResponse response) throws Exception {
		String result = "";
		PrintWriter out = response.getWriter();
		boolean flag = false;
		ArrayList rt = new ArrayList();
		try {
			WTUser currentuser = (WTUser)SessionHelper.getPrincipal();
			log.info("=========getAccessForMaterials  name:" + currentuser.getName());
			// BOM工程师 Asi-BOM工程师 无源-BOM工程师 LTPS-BOM工程师 CTP-BOM工程师 Asi（上海）-BOM工程师
			Enumeration members = null;
			wt.org.WTGroup users = OrganizationServicesHelper.manager.getGroup("Asi-BOM工程师");
			log.info("=========getAccessForMaterials  Asi-BOM工程师  users 1:" + users);
			users = WorkFlowUtil.getGroup("Asi-BOM工程师");
			log.info("=========getAccessForMaterials  Asi-BOM工程师  users 2:" + users);
			log.info("");
			if (users != null) {
				members = wt.org.OrganizationServicesHelper.manager.members((wt.org.WTGroup) users, false);
				while (members != null && members.hasMoreElements()) {
					wt.org.WTPrincipal prin = (wt.org.WTPrincipal) members.nextElement();
					if (prin instanceof wt.org.WTUser) {
						if (!rt.contains(prin))
							rt.add(prin);
					} else if (prin instanceof wt.org.WTGroup) {
						if (!rt.contains(prin))
							rt.add(prin);
					}
				}
			}
			users = OrganizationServicesHelper.manager.getGroup("无源-BOM工程师");
			log.info("=========getAccessForMaterials  无源-BOM工程师  users 1:" + users);
			users = WorkFlowUtil.getGroup("无源-BOM工程师");
			log.info("=========getAccessForMaterials  无源-BOM工程师  users 2:" + users);
			// Asi-BOM工程师 无源-BOM工程师 LTPS-BOM工程师 CTP-BOM工程师 Asi（上海）-BOM工程师
			if (users != null) {
				members = wt.org.OrganizationServicesHelper.manager.members((wt.org.WTGroup) users, false);
				while (members != null && members.hasMoreElements()) {
					wt.org.WTPrincipal prin = (wt.org.WTPrincipal) members.nextElement();
					if (prin instanceof wt.org.WTUser) {
						if (!rt.contains(prin))
							rt.add(prin);
					} else if (prin instanceof wt.org.WTGroup) {
						if (!rt.contains(prin))
							rt.add(prin);
					}
				}
			}
			users = OrganizationServicesHelper.manager.getGroup("LTPS-BOM工程师");
			log.info("=========getAccessForMaterials  LTPS-BOM工程师  users 1:" + users);
			users = WorkFlowUtil.getGroup("LTPS-BOM工程师");
			log.info("=========getAccessForMaterials  LTPS-BOM工程师  users 2:" + users);
			// Asi-BOM工程师 无源-BOM工程师 LTPS-BOM工程师 CTP-BOM工程师 Asi（上海）-BOM工程师
			if (users != null) {
				members = wt.org.OrganizationServicesHelper.manager.members((wt.org.WTGroup) users, false);
				while (members != null && members.hasMoreElements()) {
					wt.org.WTPrincipal prin = (wt.org.WTPrincipal) members.nextElement();
					if (prin instanceof wt.org.WTUser) {
						if (!rt.contains(prin))
							rt.add(prin);
					} else if (prin instanceof wt.org.WTGroup) {
						if (!rt.contains(prin))
							rt.add(prin);
					}
				}
			}
			users = OrganizationServicesHelper.manager.getGroup("CTP-BOM工程师");
			log.info("=========getAccessForMaterials  CTP-BOM工程师  users 1:" + users);
			users = WorkFlowUtil.getGroup("CTP-BOM工程师");
			log.info("=========getAccessForMaterials  CTP-BOM工程师  users 2:" + users);

			// Asi-BOM工程师 无源-BOM工程师 LTPS-BOM工程师 CTP-BOM工程师 Asi（上海）-BOM工程师
			if (users != null) {
				members = wt.org.OrganizationServicesHelper.manager.members((wt.org.WTGroup) users, false);
				while (members != null && members.hasMoreElements()) {
					wt.org.WTPrincipal prin = (wt.org.WTPrincipal) members.nextElement();
					if (prin instanceof wt.org.WTUser) {
						if (!rt.contains(prin))
							rt.add(prin);
					} else if (prin instanceof wt.org.WTGroup) {
						if (!rt.contains(prin))
							rt.add(prin);
					}
				}
			}
			users = OrganizationServicesHelper.manager.getGroup("Asi（上海）-BOM工程师");
			log.info("=========getAccessForMaterials  Asi（上海）-BOM工程师  users 1:" + users);

			users = WorkFlowUtil.getGroup("Asi（上海）-BOM工程师");
			log.info("=========getAccessForMaterials  Asi（上海）-BOM工程师  users 2:" + users);

			// Asi-BOM工程师 无源-BOM工程师 LTPS-BOM工程师 CTP-BOM工程师 Asi（上海）-BOM工程师
			if (users != null) {
				members = wt.org.OrganizationServicesHelper.manager.members((wt.org.WTGroup) users, false);
				while (members != null && members.hasMoreElements()) {
					wt.org.WTPrincipal prin = (wt.org.WTPrincipal) members.nextElement();
					if (prin instanceof wt.org.WTUser) {
						if (!rt.contains(prin))
							rt.add(prin);
					} else if (prin instanceof wt.org.WTGroup) {
						if (!rt.contains(prin))
							rt.add(prin);
					}
				}
			}
			
			//管理员
			users = WorkFlowUtil.getGroup("Administrators");
			log.info("=========getAccessForMaterials  Asi-BOM工程师  users 2:" + users);
			log.info("");
			if (users != null) {
				members = wt.org.OrganizationServicesHelper.manager.members((wt.org.WTGroup) users, false);
				while (members != null && members.hasMoreElements()) {
					wt.org.WTPrincipal prin = (wt.org.WTPrincipal) members.nextElement();
					if (prin instanceof wt.org.WTUser) {
						if (!rt.contains(prin))
							rt.add(prin);
					} else if (prin instanceof wt.org.WTGroup) {
						if (!rt.contains(prin))
							rt.add(prin);
					}
				}
			}
			
			log.info("========rt size:"+rt.size());
			for (int p = 0; p < rt.size(); p++) {
				log.info("====:"+rt.get(p));
				if(rt.get(p) instanceof WTUser){
					wt.org.WTUser user = (wt.org.WTUser) rt.get(p);
					String username = user.getName();
					if (username.equalsIgnoreCase(currentuser.getName())
							|| currentuser.getName().equalsIgnoreCase("Administrator")
							|| currentuser.getName().equalsIgnoreCase("tmadmin")) {
						log.info("=======getAccessForMaterials equals=====");
						flag = true;
						break;
					}
				}else if(rt.get(p) instanceof WTGroup) {
					WTGroup group = (wt.org.WTGroup) rt.get(p);
					log.info("=======getAccessForMaterials group====="+group.getName());
				}
				

			}
		} catch (WTException e) {
			e.printStackTrace();
		}
		out.println(flag);
	}
	
	/**
	 * 获取分类属性显示名称
	 * 
	 * @param number
	 * @return
	 */
	public String getMaterialsClassificationByName(String name) {
		JSONObject result = new JSONObject();
		String classificationATT = "";
		try {
			List<HashMap<String, String>>  list =  ClassificationUtil.getClassificationAttByName(name);
			if (list.size() == 0) {
				result.put("datalist", "");
				return result.toString();
			}
			JSONObject object = new JSONObject();
			for(HashMap<String, String> map : list ){
				String displayname = map.get("displayname");
				String value = map.get("value");
				String key = map.get("key");
				System.out.println("====displayname:"+displayname+"==key:"+key+"---value:"+value);
				object.put(displayname, value==null?"":value);
			}
			result.put("datalist", object);
		}catch(Exception e){
			log.error(e.getMessage(), e);;
		}
		return result.toString();
	}
}
